# coding:utf-8

import os
import csv
import time


class MyDictionary(object):
    def __init__(self, aimPath, newDirName=''):
        """
        :param aimPath: str
        :param newDirName: str
        to init/read a dir contains [a-z].csv, stateLog.txt
        """
        # root infor
        self.isNew = len(newDirName.strip())
        self.RootPath = os.path.join(aimPath, newDirName)

        # path infor
        self.DicPath = os.path.join(self.RootPath, "MyWordDatabase")
        self.DicNewWordPath = os.path.join(self.RootPath, "NewWords.csv")
        self.DicLogPath = os.path.join(self.RootPath, "MyDicStateLog.csv")
        self.DicDraftPath = os.path.join(self.RootPath, "Drafts")

        # dictionany infor
        self.DicTableHead = "word,part_of_speech,Chinese_meaning,example_sentence\n"
        self.DicNewStatus = {}  # to record how many new words
        self.DicNewData = {}
        for i in range(ord("A"), ord("Z") + 1):
            self.DicNewData[chr(i)] = []
            self.DicNewStatus[chr(i)] = 0
        self.DicDraftData = []

        # funcs
        self.initDictionary()

    def initDictionary(self):
        """
        :return: bool
        build a new word dictionary dir and log
        """
        if self.isNew:
            # for safety concerns, end the func if aim dir is not empty
            print(f"ready to build new file path:\n {self.RootPath}")
            if not os.path.exists(self.RootPath):
                os.makedirs(self.RootPath)
                print("built OK")
            elif len(os.listdir(self.RootPath)):
                print(f"{self.RootPath} is not an empty dir, please change a dir name to retry")
                return 1
            """
            init file:
            |__MyWordDatabase/[A-Z].csv 
            |__MyDicStateLog.csv (as checkpoint. please do not delete )
            |__NewWords.csv 
            |__Drafts
            """
            # MyWordDatabase/[A-Z].csv
            os.makedirs(self.DicPath)
            li = [chr(i) for i in range(ord("A"), ord("Z") + 1)]
            for i in li:
                with open(os.path.join(self.DicPath, f"{i}.csv"), "w+") as f:
                    f.write(self.DicTableHead)

            # Log
            with open(self.DicLogPath, "a+") as f:
                # f.write(str({time.time():self.DicState}+"\n"))
                li = ','.join([chr(i) for i in range(ord("A"), ord("Z") + 1)])
                f.write(','.join(["time", li]) + '\n')

            # NewWords.csv
            with open(self.DicNewWordPath, "a+") as f:
                f.write(self.DicTableHead)

            # Draft
            os.makedirs(self.DicDraftPath)

            # add add_new.bat
            PathNow = os.getcwd()
            with open(os.path.join(self.RootPath, "AddNewWords.bat"), "w+")as f:
                addNewPath = os.path.join(PathNow, "addNew.py")
                f.write(f"python {addNewPath} {self.RootPath}")
            return 0

        else:
            # load dic
            print(f'ready to load file in:\n {self.RootPath}')
            fileList = os.listdir(self.RootPath)
            if os.path.basename(self.DicLogPath) not in fileList:
                print(f"not a init MyDictionary project DIR \n please add '{self.DicLogPath}' and retry")
                return 1
            else:
                pass
                # todo
            # with open(self.DicLogPath,"r") as f:

    def addNewWord(self):
        """
        only the line whose num of non-empty cell < 3 will be recorded as new words
        the others will be regarded as draft and be added in draft_{time_stamp}.csv
        """
        newWords = []  # temp, judge is new?
        with open(self.DicNewWordPath)as f:
            wordsline = f.readlines()[1::]
        # is new word? is draft?
        for index, line in enumerate(wordsline):
            inLine = line[0:-1].strip(" ,\\").split(",")  # delete "\n"

            if inLine[0] not in newWords and len(inLine) >= 3:
                dicIndex = inLine[0].strip()[0].upper()
                newWords.append(inLine[0])
                self.DicNewData[dicIndex].append(line)
                self.DicNewStatus[dicIndex] += 1  # count
            else:
                self.DicDraftData.append(line)

        # add new words to my dictionary
        for l in range(ord("A"), ord("Z") + 1):
            dicPath = os.path.join(self.DicPath, f"{chr(l)}.csv")
            with open(dicPath, "a") as f:
                f.writelines(self.DicNewData[chr(l)])
        # add draft
        with open(os.path.join(self.DicDraftPath, f"draft_{int(time.time())}.csv"), "a+") as f:
            f.writelines(self.DicDraftData)
        # delete original file and add new
        os.remove(self.DicNewWordPath)
        with open(self.DicNewWordPath, "a+") as f:
            f.write(self.DicTableHead)

        # write log
        with open(self.DicLogPath, "a")as f:
            li = ",".join([str(self.DicNewStatus[chr(i)]) for i in range(ord("A"), ord("Z") + 1)])
            f.write(','.join([str(int(time.time())), li]) + "\n")


if __name__ == '__main__':
    # testDicName = f"testDictionary_{int(time.time())}"
    # myDic = MyDictionary(aimPath=r".", newDirName=testDicName)
    # # add test data
    # with open(myDic.DicNewWordPath, "a") as f:
    #     f.write("asd,dfgsd,hjk,hk\nasd,dfgsd,hjk,hk\n,hk,,\n,dfs,,\n,,dsgf,\n,,,sf\n")
    # myDic.addNewWord()
    pass